import { axios, api } from '../Axios/index.js';
import { Loading } from 'element-ui';
import _ from 'lodash';

import { format } from './molle.js';

let loading;
function openLoading() {
  loading = Loading.service({
    lock: true,
    background: 'rgba(255,255,255,0.6)',
  });
}
function closeLoading() {
  loading.close();
}

//ctx:上下文，这里是store本身
//payload:有效载荷，这里指额外参数对象

export default {
  testActions(ctx, payload) {
    let opt = Object.assign(
      ctx.getters.getOpt,
      payload,
    );
    console.log(opt)
  },
  get_App_Cus(ctx, payload) {
    openLoading()
    // ctx.cusList_Page_state.isWSLock = true;
    let pageOpt = ctx.getters.getPages
    if (payload.isOutpage) {
      pageOpt.page = 1
      pageOpt.current = 1
    }
    let app = ctx.getters.getAppID(false);
    let pid = ctx.getters.getPlatformId;
    let opt = _.mergeWith(
      {},
      ctx.getters.getOpt,             //条件组//{selftag:[18],}
      ctx.getters.getCEID(false),      //员工id,从url取得
      {
        eSCompanyId: (pid == app.eSCompanyId) ? app.eSCompanyId : pid,
        agentid: (pid == app.eSCompanyId) ? app.agentid : 0,
        searchName: ''
      },                               //企业id,默认 '',平台id,默认0
      pageOpt,
      payload,
      (objValue, srcValue, key, object, source, stack) => {
        if (key == 'unselftag' && !_.isUndefined(objValue) && _.isArray(srcValue)) {
          return objValue.split(',').concat(srcValue).join(',')
        }
        return
      }
    );
    // console.log('获取客户列表/工作台(左中0/中1)', opt);
    api.get_App_Cus(opt).then((res) => {
      let appList = (opt.state == 0) ? format.appList(res.data.workBenches.workBenchList) : [];
      let cusList = format.cusList(res.data.list);
      return {
        appList: appList,
        cusList: cusList,
        total: res.data.count,
        maopao: res.data.maopaoCount,
        noReadCountConditions: res.data.noReadCountConditions,
        noReadCountTotal: res.data.noReadCountTotal,
      }
    }).then((res) => {
      if (opt.state == 0) {
        ctx.commit('setListApp', res.appList);
      } else {
        ctx.commit('fixAppUnread', {
          pid: _.get(opt, 'eSCompanyId', null),
          aid: _.get(opt, 'agentid', null),
          unread: res.noReadCountTotal,
        })
      }
      ctx.commit('setListCus', res.cusList);
      ctx.commit('setCusList_Page_state', {
        arr: res.cusList,
        page: { current: opt.current, total: res.total },
        status: { total: res.total, maopao: res.maopao },
      })
      closeLoading();
    })
  },//获取客户列表\工作台
  getFromSource(ctx, payload) {
    api.getFromSource().then((res) => {
      console.log(res)
      if (res.data.code == 200) {
        return Promise.resolve(res.data.data)
      }
    }).then((res) => {
      ctx.commit('setFromSources', res)
    }).catch(() => { })

  },
  // getChatMsgs(ctx, payload) {
  //   return
  // },//获取聊天记录,原有的逻辑不再此处处理，移植到组件内处理
  getSelfTags(ctx, payload) {
    let opt = Object.assign({}, payload,);
    api.selfTag.getGroup(opt).then((res) => {
      if (res.data.code == 200) {
        return Promise.resolve(res.data.data);
      }
    }).then((res) => {
      ctx.commit('setSelfTags', res);//填充自用标签列表
    })
  },
  getLabelList(ctx, payload) {
    let opt = Object.assign(
      ctx.getters.getESID(false),
      payload,
    );
    // console.log('获取平台标签',opt)
    api.getLabelList(opt).then((res) => {
      let list = res.data.data.map((v) => {
        return {
          id: v.tags_Id,
          text: v.tags_Name,
          checked: false,
        }
      })
      ctx.commit('setLabelList', list);//填充新数据
      ctx.commit('setAObjLabel', { action: 'clear' })//清空可能被选过的数据
    }).catch((err) => {
      console.log(err)
    })
  },//获取平台标签
  getCusTags(ctx, payload) {
    let opt = Object.assign(
      ctx.getters.getESID(false),
      ctx.getters.getCusId(false),
      payload,
    );
    // console.log('获取用户的标签', opt)
    api.getCusTags(opt).then((res) => {
      if (res.data.code == 200) {
        let arr = res.data.data.map((v) => {
          return {
            id: v.tags_Id,
            text: v.tags_Name,
          }
        });
        ctx.commit('setCusTags', arr)
      }
    }).catch((err) => {
      console.error(err)
    })
  },//获取用户的标签
  getOrgTree(ctx, payload) {
    let opt = Object.assign(
      // ctx.getters.getCEID(false),
      ctx.getters.getESID(false),
      ctx.getters.getAppID(false),
      payload,
    );
    console.log('获取应用的部门、人员(中间树状组织结构)', opt)
    api.getOrgTree(opt).then((res) => {

      let resdata = res.data.data.agentAllowPartyList;
      //后端需要重写接口数据结构,前端等后端接口变更后重写递归方法
      function setChild(tree, json, paId) {
        // console.log(paId)
        let pNode = json.agentAllowUserList;
        let pLen = Array.isArray(pNode) ? pNode.length : 0;
        let uNode = json.agentAllowPartyList;
        let uLen = Array.isArray(uNode) ? uNode.length : 0;
        let obj = {
          userId: json.partyid || json.usersId,
          isParty: Boolean(json.partyid),
          label: json.partyName || json.name,
          disabled: (("isAllow" in json) ? !json.isAllow : false),
        }
        obj.id = `${paId}_${json.partyid || json.usersId}`;
        if ("usersId" in json) {
          obj.esCompanyId = opt.esCompanyId;
          obj.cusId = json.usersId;
          obj.cusName = json.name;
          // obj.cusTel = json.tel;
        }
        if ((pLen + uLen) > 0) {
          obj.children = new Array();
        }
        if (pLen > 0) {
          for (let i in pNode) {
            setChild(obj.children, pNode[i], obj.id,)
          }
        }
        if (uLen > 0) {
          for (let i in uNode) {
            setChild(obj.children, uNode[i], obj.id,)
          }
        }
        tree.push(obj)
        return tree;
      }
      let tree = resdata.map((v) => { return setChild([], v, '_')[0] });
      console.log('%c [ action tree ]', 'font-size:13px; background:pink; color:#bf2c9f;', tree)

      ctx.commit('setTreeOrg', tree);
      ctx.commit('setATreeOrg', { action: 'clear' })
    }).catch((err) => {
      console.error(err)
    })
  },//获取应用的部门、人员
  setAppTop(ctx, payload) {
    let opt = Object.assign(
      ctx.getters.getCEID(false),
      ctx.getters.getESID(false),
      payload,
    );
    // console.log('应用置顶', opt);
    api.setAppTop(opt).then((res) => {
      if (res.data.code == 200) { }
    }).catch((err) => {
      console.error(err)
    })
  },//应用置顶
  setAppHide(ctx, payload) {
    let opt = Object.assign(
      ctx.getters.getCEID(false),
      ctx.getters.getESID(false),
      payload
    );
    // console.log('应用隐藏', opt);
    api.setAppHide(opt).then((res) => {
      if (res.data.code == 200) { }
    }).catch((err) => {
      console.error(err)
    })
  },//应用隐藏
  cancelAllAppHide(ctx, payload) {
    let opt = Object.assign(
      ctx.getters.getCEID(false),
      ctx.getters.getESID(false),
      payload
    );
    // console.log('取消所有应用隐藏', opt);
    api.cancelAllAppHide(opt).then((res) => {
      if (res.data.code == 200) { }
    }).catch((err) => {
      console.error(err)
    })
  },//取消所有应用隐藏

  sendMsg(ctx, payload) {
    let opt = Object.assign(
      ctx.getters.getESID(false),
      ctx.getters.getAppID(false),
      payload,
    );
    // console.log('发送消息',opt)
  },//发送消息

  //获取用户的所有员工的ID??

  // //修改用户标签?? 这个功能废弃掉转$api直接处理

  // updataUserName(ctx, payload) {
  //   let opt = Object.assign(
  //     ctx.getters.getESID(false),
  //     ctx.getters.getCusId(false),
  //     payload
  //   );
  //   // console.log('修改用户名字、昵称',opt)
  //   api.editNickname(opt).then((res) => {
  //     if (res.status == 200) {
  //       ctx.commit('updataCusNickName', {
  //         cusId: opt.usersId,
  //         newName: opt.name
  //       })
  //     }
  //   }).catch((err) => {
  //     console.error(err)
  //   })
  // },//修改用户名字、昵称

  setMsg2Readed(ctx, payload) {
    let opt = Object.assign(
      ctx.getters.getCEID(false),
      payload
    );
    console.log('将客户所有消息标为已读', opt);
    api.setMsg2Readed(opt).then((res) => {
      if (res.data.code == 200) {
        // ctx.commit("clearCusUnread", opt)
        // 原版手动清空红点读数，后改为等待ws广播再倒减数
      }
    }).catch((err) => {

    })
  }
  //将客户所有消息标为已读
}